package megrez.common.core.web;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * 异常堆栈信息过滤
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
public class ThrowableFiltered {
    public static final ThrowableFiltered INSTANCE = new ThrowableFiltered();

    private String[] includePackageList = { "megrez" };
    private static final String PFX_AT = "\tat ";

    public String renderLine(Throwable throwable) {
        return String.join(System.lineSeparator(), renderArray(throwable));
    }

    public List<String> renderArray(Throwable throwable) {
        ArrayList<String> lines = new ArrayList<>();
        lines.addAll(render(throwable));

        Throwable cause = throwable.getCause();
        while(cause != null) {
            lines.add(getMessage(cause));
            cause = cause.getCause();
        }
        return lines;
    }

    protected List<String> render(Throwable throwable) {
        ArrayList<String> lines = new ArrayList<>();
        lines.add(getMessage(throwable));

        Stream.of(throwable.getStackTrace())
                .filter(this::isInclude)
                .map(ste -> PFX_AT + ste.toString())
                .forEach(lines::add);
        return lines;
    }

    protected String getMessage(Throwable throwable) {
        return throwable.getClass().getName() + " : " + throwable.getMessage();
    }

    protected boolean isInclude(StackTraceElement ste) {
        for (String packageName : includePackageList) {
            if (ste.getClassName().startsWith(packageName)) {
                return true;
            }
        }

        return false;
    }   
}
